#!/bin/bash

PEAC_VERSION=0.36

function ShowHelp() {
  echo ""
  echo "./peac proof start"
  echo "./peac proof stop"
  echo ""
}

if [ $# -lt 1 ];then
  ShowHelp
  return 1
fi

function IdentifySystem() {
  cat $PEAC_SW_TEMPLATE_DIR/peac/peac-identify_system.pbuild > /tmp/$USER-peac-identify_system.pbuild
  echo "PEAC_identify_system " >> /tmp/$USER-peac-identify_system.pbuild
  echo "`. /tmp/$USER-peac-identify_system.pbuild`"
  rm /tmp/$USER-peac-identify_system.pbuild
}

function GetPackageDir() {
  local MY_VO=`echo $1 | awk -F ':' '{print $1}' | awk -F '@' '{print $1}'`
  local MY_NAME=`echo $1 | awk -F ':' '{print $1}' | awk -F '@' '{print $2}'`
  local MY_VER=`echo $1 | awk -F ':' '{print $3}'`
  echo "$MY_VO/$MY_NAME/$MY_VER"
}

function GetPackageVersionFromPath() {
  if [ -z "$1" ];then
    echo ""
  fi

  local MY_DIR="$1"
  local MY_VER=`basename $MY_DIR`
  MY_DIR=`dirname $MY_DIR`
  local MY_NAME=`basename $MY_DIR`
  MY_DIR=`dirname $MY_DIR`
  local MY_VO=`basename $MY_DIR`
  echo "$MY_VO@$MY_NAME::$MY_VER"
}


function CreateSSHWithoutPassword() {

  if [ ! -f wk.cf ];then
    echo "Create wk.cf first !!!"
    exit 1
  fi

  if [ ! -f ~/.ssh/config ];then
    echo "StrictHostKeyChecking no" > ~/.ssh/config
  else
    TMP=`cat ~/.ssh/config | grep StrictHostKeyChecking`
    if [ -z "$TMP" ];then
      echo "StrictHostKeyChecking no" > ~/.ssh/config
    fi
  fi

  if [ ! -f ~/.ssh/id_dsa ];then
    ssh-keygen -t dsa
  fi

  cat ~/.ssh/id_dsa.pub > ~/.ssh/authorized_keys

  for MY_HOST in `cat wk.cf | grep -v '#' `; do
    echo "Copying ssh files to $MY_HOST ..."
#     ssh $MY_HOST rm -Rf ~/.ssh
    scp -r ~/.ssh $MY_HOST:~
  done

}

function GeneratePoDSSHConfig() {
  if [ ! -f wk.cf ];then
    echo "Create wk.cf first !!!"
    exit 1
  fi

  rm -f $PEAC_POD_WK_CF
  let NUM=1
  for MY_HOST in `cat wk.cf | grep -v '#' `; do
    echo "Adding host $MY_HOST with id r$NUM"
    echo "r$NUM, $USER@$MY_HOST , , $PEAC_SYS_DIR/ ," >> $PEAC_POD_WK_CF

    if [ "$1" == "clean" ];then
      echo "Cleaning  direcotry $PEAC_SYS_DIR on worker $MY_HOST"
      ssh $MY_HOST rm -Rf $PEAC_SYS_DIR
      ssh $MY_HOST mkdir -p $PEAC_SYS_DIR
    else
      echo "Creating direcotry $PEAC_SYS_DIR on worker $MY_HOST"
      ssh $MY_HOST mkdir -p $PEAC_SYS_DIR
    fi
    let NUM=$NUM+1
    
  done

}

function TrickPoD() {
  if [ -d $PEAC_POD_SYS_DIR ];then
    rm -Rf $PEAC_POD_SYS_DIR
  fi
  mv $HOME/.PoD $PEAC_POD_SYS_DIR
  ln -s $PEAC_POD_SYS_DIR $HOME/.PoD
}

function InitPoDServer() {
# PrepareSoftDistDir

cat > $PEAC_POD_SYS_DIR/PoD.cfg <<EOF
[server]
work_dir=$PEAC_POD_SYS_DIR
logfile_dir=$PEAC_POD_SYS_DIR/log
logfile_overwrite=yes
log_level=1
agent_shutdown_if_idle_for_sec=0
agent_local_client_port_min=20000
agent_local_client_port_max=25000
xproof_ports_range_min=$PEAC_POD_MASTER_PORT
xproof_ports_range_max=$PEAC_POD_MASTER_PORT
agent_ports_range_min=22001
agent_ports_range_max=23000
agent_threads=5
agent_node_readbuffer=5000
packet_forwarding=no
proof_cfg_entry_pattern=worker %host% port=%port%
[worker]
work_dir=\$POD_LOCATION/
logfile_dir=\$POD_LOCATION/
logfile_overwrite=yes
log_level=1
set_my_rootsys=yes
my_rootsys=\$ROOTSYS
agent_shutdown_if_idle_for_sec=0
xproof_ports_range_min=21001
xproof_ports_range_max=22000
agent_node_readbuffer=5000
[lsf_plugin]
email_job_output=no
upload_job_log=no
[pbs_plugin]
upload_job_log=no
[ge_plugin]
upload_job_log=no
options_file=\$POD_LOCATION/etc/Job.oge.option
[condor_plugin]
upload_job_log=no
options_file=\$POD_LOCATION/etc/Job.condor.option
EOF

rm -f $PEAC_POD_SYS_DIR/user_xpd.cf.1
echo "if named PoDServer" >> $PEAC_POD_SYS_DIR/user_xpd.cf.1
echo " xpd.workdir $PEAC_SYS_DIR/proofbox" >> $PEAC_POD_SYS_DIR/user_xpd.cf.1
echo "fi" >> $PEAC_POD_SYS_DIR/user_xpd.cf.1

if [ -f $PEAC_SYS_DIR/user_xpd.cf.2 ];then
  cp $PEAC_SYS_DIR/user_xpd.cf.2 $PEAC_POD_SYS_DIR/user_xpd.cf.2
fi

cat > $PEAC_POD_SYS_DIR/user_worker_env.sh <<EOF
#!/bin/bash

MY_WK_PWD=\`pwd\`
cd ../
rm -f peac
rm -f peac.cf
wget http://peac.googlecode.com/svn/trunk/scripts/peac
chmod +x peac
./peac
echo "" >> peac.cf
echo "export PEAC_MASTER_HOSTNAME=$PEAC_MASTER_HOSTNAME" >> peac.cf
echo "" >> peac.cf
echo "export PEAC_SW_XROOTD_PORT=$PEAC_SW_XROOTD_PORT" >> peac.cf

MY_SYSTEM=\`./peac sw system | tail -n 1\`

./peac sw install $PEAC_XROOT_VERSION_CURRENT
if [ -f $PEAC_SW_DIR/\$MY_SYSTEM/$(GetPackageDir $PEAC_XROOT_VERSION_CURRENT)/peac-env.sh ];then
  source $PEAC_SW_DIR/\$MY_SYSTEM/$(GetPackageDir $PEAC_XROOT_VERSION_CURRENT)/peac-env.sh
else
  echo "$PEAC_SW_DIR/\$MY_SYSTEM/$(GetPackageDir $PEAC_XROOT_VERSION_CURRENT)/peac-env.sh is not valid !!!"
  return 1
fi

# copying dep files
xrdcp -f root://$PEAC_MASTER_HOSTNAME:$PEAC_SW_XROOTD_PORT/$PEAC_SW_PACKAGE_DEP_DIR/VO_PEAC.dep $PEAC_SW_PACKAGE_DEP_DIR/VO_PEAC.dep
xrdcp -f root://$PEAC_MASTER_HOSTNAME:$PEAC_SW_XROOTD_PORT/$PEAC_SW_PACKAGE_DEP_DIR/VO_ALICE.dep $PEAC_SW_PACKAGE_DEP_DIR/VO_ALICE.dep

xrdcp -f root://$PEAC_MASTER_HOSTNAME:$PEAC_SW_XROOTD_PORT/$PEAC_SW_PACKAGE_DEP_DIR/VO_PEAC_WK.soft $PEAC_SW_PACKAGE_DEP_DIR/VO_PEAC_WK.soft
# PEAC_ROOT_VERSION_CURRENT="\`cat $PEAC_SW_PACKAGE_DEP_DIR/VO_PEAC_WK.soft | grep \"VO_PEAC@ROOT\"\`"
PEAC_ROOT_VERSION_CURRENT="\`cat $PEAC_SW_PACKAGE_DEP_DIR/VO_PEAC_WK.soft | grep \"ROOT\"\`"
./peac sw install $PEAC_ROOT_VERSION_CURRENT
if [ -f $PEAC_SW_DIR/\$MY_SYSTEM/$(GetPackageDir $PEAC_ROOT_VERSION_CURRENT)/peac-env.sh ];then
  source $PEAC_SW_DIR/\$MY_SYSTEM/$(GetPackageDir $PEAC_ROOT_VERSION_CURRENT)/peac-env.sh
else
  echo "$PEAC_SW_DIR/\$MY_SYSTEM/$(GetPackageDir $PEAC_ROOT_VERSION_CURRENT)/peac-env.sh is not valid !!!"
fi

xrdcp -f root://$PEAC_MASTER_HOSTNAME:$PEAC_SW_XROOTD_PORT/$PEAC_SW_PACKAGE_DEP_DIR/VO_ALICE.soft $PEAC_SW_PACKAGE_DEP_DIR/VO_ALICE.soft
./peac sw sync VO_ALICE

cd \$MY_WK_PWD

export GCLIENT_SERVER_LIST="pcapiserv08.cern.ch:10000|"
echo "MV ROOTSYS is \$ROOTSYS"
EOF

cat > $PEAC_SW_DIR/xrd-simple.cf <<EOF
all.export $PEAC_SW_DIR r/w
xrd.port $PEAC_SW_XROOTD_PORT
all.pidpath $PEAC_SW_XRD_DIR
all.adminpath $PEAC_SW_XRD_DIR/admin
EOF
CreateDir $PEAC_SW_XRD_DIR/admin
CreateDir $PEAC_LOG_DIR/xrd
}

function StartStopPodServer() {

  if [ ! -f $PEAC_SW_DIR/$(IdentifySystem)/$(GetPackageDir $PEAC_POD_VERSION_CURRENT)/PoD_env.sh ];then
    echo "Pod is not installed !!!"
    exit 100
  fi

  if [ ! -f $PEAC_SW_DIR/$(IdentifySystem)/$(GetPackageDir $PEAC_ROOT_VERSION_CURRENT)/peac-env.sh ];then
    echo "ROOT $PEAC_SW_DIR/$(IdentifySystem)/$(GetPackageDir $PEAC_ROOT_VERSION_CURRENT)/peac-env.sh is not valid !!!"
    exit 1
  fi
  source $PEAC_SW_DIR/$(IdentifySystem)/$(GetPackageDir $PEAC_ROOT_VERSION_CURRENT)/peac-env.sh

  if [ -z $ROOTSYS ];then
      echo "ROOT is invalid or doesn't exist !!!!"
      exit 1
  fi 

  if [ "$1" == "start" ];then
    echo "Starting PoD ..."
#     killall xproofd > /dev/null 2>&1
    rm -Rf $HOME/.PoD
    source  $PEAC_SW_DIR/$(IdentifySystem)/$(GetPackageDir $PEAC_POD_VERSION_CURRENT)/PoD_env.sh
    TrickPoD

    InitPoDServer
    # xrootd for sw
    DoStartStopSWXrootd $1
    pod-server $1
    echo "Sleeping for 2 sec ..."
    sleep 2
    chmod 755 /tmp/PoD_*/*
    
    # prepare software 
#     PrepareSoftDistDir
  elif [ "$1" == "stop" ];then
    echo "Stoping PoD ..."
    source  $PEAC_SW_DIR/$(IdentifySystem)/$(GetPackageDir $PEAC_POD_VERSION_CURRENT)/PoD_env.sh
    pod-server $1
    DoStartStopSWXrootd $1
  fi

  echo "Done"
}

function DoStartStopSWXrootd() {

    if [ "$1" == "start" ];then
      InitPoDServer
      # xrootd for sw
      source $PEAC_SW_DIR/$(IdentifySystem)/$(GetPackageDir $PEAC_XROOT_VERSION_CURRENT)/peac-env.sh
#       echo "We are taking xrootd from `which xrootd`"
      if [ -f $PEAC_SW_XRD_DIR/xrootd.pid ];then
	kill -0 `cat $PEAC_SW_XRD_DIR/xrootd.pid` > /dev/null 2>&1
	if [ "$?" != "0" ];then
	  rm -f $PEAC_SW_XRD_DIR/xrootd.pid
	fi
      fi
      xrootd -b -c $PEAC_SW_DIR/xrd-simple.cf -l $PEAC_LOG_DIR/xrd/xrd-software.log -R $PEAC_USER
      sleep 1
      local MY_XRD_PID=`cat $PEAC_SW_XRD_DIR/xrootd.pid`
      kill -0 $MY_XRD_PID > /dev/null 2>&1
      if [ "$?" == "0" ];then
        echo "Xrootd started with PID $MY_XRD_PID ..."
      fi
    elif [ "$1" == "stop" ];then
      if [ -f $PEAC_SW_XRD_DIR/xrootd.pid ];then
        echo "Killing xrootd with PID `cat $PEAC_SW_XRD_DIR/xrootd.pid` ..."
        kill `cat $PEAC_SW_XRD_DIR/xrootd.pid` > /dev/null 2>&1
        rm -f $PEAC_SW_XRD_DIR/xrootd.pid
      fi
    fi
}

function DoPoDWorkersAction() {

#   if [ -n "$2" ];then
#     PEAC_OPT_CURRENT_ROOT_VER="$2"
#   fi
  local MY_CMD=$1
  if [ "$MY_CMD" == "start" ]; then
    MY_CMD="--submit"
  fi
  if [ "$MY_CMD" == "stop" ]; then
    MY_CMD="--clean"
  fi

  if [ ! -f $PEAC_SW_DIR/$(IdentifySystem)/$(GetPackageDir $PEAC_ROOT_VERSION_CURRENT)/peac-env.sh ];then
    echo "ROOT $PEAC_SW_DIR/$(IdentifySystem)/$(GetPackageDir $PEAC_ROOT_VERSION_CURRENT)/peac-env.sh is not valid !!!"
    exit 100
  fi
  source $PEAC_SW_DIR/$(IdentifySystem)/$(GetPackageDir $PEAC_ROOT_VERSION_CURRENT)/peac-env.sh

  if [ -z $ROOTSYS ];then
      echo "ROOT is invalid or doesn't exist !!!!"
      exit 101
  fi 

  if [ ! -f  $PEAC_SW_DIR/$(IdentifySystem)/$(GetPackageDir $PEAC_POD_VERSION_CURRENT)/PoD_env.sh ];then
    echo "Pod is not installed !!!"
    exit 102
  fi

  source  $PEAC_SW_DIR/$(IdentifySystem)/$(GetPackageDir $PEAC_POD_VERSION_CURRENT)/PoD_env.sh
  pod-ssh -c $PEAC_POD_WK_CF $MY_CMD
  if [ $? == "0" ];then
    if [ "$MY_CMD" == "--submit" ];then
      echo ""
      echo "+++++++++++++++++++++++++++++++++++++++++++++++++++++++"
      echo ""
      echo "Now you can do in root: "
      echo ""
      echo "   root [] TProof::Open(\"`pod-info -c`\")"
      echo ""
      echo "+++++++++++++++++++++++++++++++++++++++++++++++++++++++"
    fi
  fi
}

function CheckPeacSW() {
  if [ -z "$ROOTSYS" ];then
    echo "source VO_PEAC@ROOT package first !!!!"
    exit 1
  fi

  if [ ! -f $ROOTSYS/peac-env.sh ];then
      echo "$ROOTSYS/peac-env.sh is not valid for VO_PEAC@ROOT !!!!"
    exit 2
  fi
  PEAC_ROOT_VERSION_CURRENT=$(GetPackageVersionFromPath $ROOTSYS)
  echo "$PEAC_ROOT_VERSION_CURRENT" > $PEAC_SW_PACKAGE_DEP_DIR/VO_PEAC_WK.soft
  echo "Using root $PEAC_ROOT_VERSION_CURRENT ..."
}

function GetLatestVersionOfPackage() {
  local MY_VO=`echo $1 | awk -F ':' '{print $1}' | awk -F '@' '{print $1}'`
  local MY_NAME=`echo $1 | awk -F ':' '{print $1}' | awk -F '@' '{print $2}'`
  for MY_TMP_VER in `ls -t $PEAC_SW_DIR/$(IdentifySystem)/$MY_VO/$MY_NAME`;do
    if [ -n "$MY_TMP_VER" ];then
      echo "$MY_VO@$MY_NAME::$MY_TMP_VER"
      return
    fi
  done

  echo ""
}

PEAC_POD_VERSION_CURRENT=$(GetLatestVersionOfPackage VO_PEAC@PoD)
PEAC_XROOT_VERSION_CURRENT=$(GetLatestVersionOfPackage VO_PEAC@Xrootd)

if [ -z "$PEAC_POD_VERSION_CURRENT" ];then
  echo ""
  echo "VO_PEAC@PoD version is not set or not installed !!!"
  echo ""
fi

if [ -z "$PEAC_XROOT_VERSION_CURRENT" ];then
  echo ""
  echo "VO_PEAC@Xrootd version is not set or not installed !!!"
  echo ""
fi

if [ "$1" == "start" ];then
  CheckPeacSW
  StartStopPodServer start
  DoPoDWorkersAction start
elif [ "$1" == "stop" ];then
  CheckPeacSW
  DoPoDWorkersAction stop
  StartStopPodServer stop
elif [ "$1" == "config" ];then
  GeneratePoDSSHConfig $2
elif [ "$1" == "ssh-init" ];then
  CreateSSHWithoutPassword
elif [ "$1" == "xrd-sw" ];then
  DoStartStopSWXrootd $2
else
  ShowHelp
fi
